package com.yzkj.siot.facade.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yzkj.siot.domain.AdminAdmin;
import com.yzkj.siot.exp.BizExp;
import com.yzkj.siot.facade.AdminFacade;
import com.yzkj.siot.result.PageParams;
import com.yzkj.siot.result.PageResponse;
import com.yzkj.siot.service.AdminAdminService;
import com.yzkj.siot.util.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Slf4j
@Service
public class AdminFacadeImpl implements AdminFacade {

    @Autowired
    AdminAdminService adminService;

    @Autowired
    PageHelper<AdminAdmin> adminPageHelper;

    @Override
    public PageResponse<AdminAdmin> page(PageParams<AdminAdmin> pageParams) {

        AdminAdmin where = pageParams.getEntity();
        QueryWrapper<AdminAdmin> adminQueryWrapper = new QueryWrapper<>();

        if (where != null) {
            adminQueryWrapper.lambda()
                    .like(!StringUtils.isEmpty(where.getEmail()), AdminAdmin::getEmail, where.getEmail())
                    .like(!StringUtils.isEmpty(where.getNickName()), AdminAdmin::getNickName, where.getNickName())
            ;
        }
        pageParams.getOrderBy().forEach(item -> adminQueryWrapper.orderBy(true, item.getIsAsc(), item.getField()));
        return adminPageHelper.queryPageOrList(adminService.getBaseMapper(), pageParams, adminQueryWrapper);
    }

    @Override
    public AdminAdmin queryOne(int id) {

        return adminService.getById(id);
    }

    @Override
    public AdminAdmin saveOrUpdate(AdminAdmin entity) {

        if (!adminService.saveOrUpdate(entity)) {
            throw new BizExp("保存管理员时出现错误");
        }

        log.info("创建新管理员 => {}", entity);
        return queryOne(entity.getId());
    }

    @Override
    public AdminAdmin remove(int id) {

        AdminAdmin admin = this.queryOne(id);

        if (!adminService.removeById(id)) {
            throw new BizExp("删除管理员失败");
        }

        log.info("管理员{}被删除", admin);
        return admin;
    }

    @Override
    public Boolean batchRemove(List<Integer> idList) {

        boolean flag = adminService.removeByIds(idList);
        if (!flag) {
            throw new BizExp("批量删除管理员失败");
        }
        log.info("批量删除管理员 => {}", idList);
        return true;
    }

    @Override
    public Boolean batchSave(List<AdminAdmin> entities) {
        return null;
    }
}
